const fs = require('fs');
const path = require('path')
const express = require('express');
const multer = require('multer');
const app = express();

const storage = multer.diskStorage({        // 设置multer参数，个性化指定上传目录和文件名
    destination: (req, file, cb) => {
        const uploadFloder = './myUpload';  // 保存上传文件的目录

        try {
            fs.accessSync(uploadFloder);
        } catch (error) {
            fs.mkdirSync(uploadFloder);
        }

        cb(null, uploadFloder);
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname);
    }
});
const upload = multer({                     // 实例化multer对象
    storage: storage
});

// 静态化资源

app.use(express.static(path.join(__dirname, 'public')))

app.get('/', (req, res) => {
    const html = fs.readFileSync('./view/index.html', { encoding: 'utf8' });  // 进行上传操作的页面

    res.send(html);
});

// 响应上传请求

app.post('/upload', upload.single('myFile'), (req, res) => {
    res.send({
        message: '响应了请求'
    });
});

app.listen(3000, () => console.log('服务器已启动!'));